/**
 * @Title: LoginInterceptor.java
 * @Package com.alex.cms.Interceptor
 * @Description: (描述该文件做什么)
 * @author Alex Lu
 * @date 2019年9月18日 下午6:53:37
 * @version V1.0
 */
package com.alex.cms.Interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alex.cms.domain.CmsUser;
import com.alex.cms.web.constants.CMSConstants;

/**
 * @ClassName: LoginInterceptor
 * @Description: 登录拦截器，用于过滤options delete请求，并且必须登录后才能访问其他页面
 * @author Alex Lu
 * @date 2019年9月18日 下午6:53:37
 *
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		boolean flag = false;
		if (request.getMethod().equals("OPTIONS")) {
			log.info(CMSConstants.REQUEST_OPTIONS_MOTHOD_INVALID);
			return flag;
		}
		if (request.getMethod().equals("DELETE")) {
			log.info(CMSConstants.REQUEST_DELETE_MOTHOD_INVALID);
			return flag;
		}
		String reqPage = request.getServletPath();
		String uri = request.getRequestURI();
		System.out.println("=============="+reqPage.startsWith("/"));
		System.out.println("请求的url============" + reqPage);
		if (reqPage.endsWith("/")||reqPage.endsWith("/reg") || reqPage.endsWith("/login") || reqPage.endsWith("/logout")) {
			flag = true;
			return flag;
		}
		HttpSession session = request.getSession(false);
		CmsUser user = (CmsUser) session.getAttribute(CMSConstants.LOGIN_USER);
		if (user != null) {
			flag = true;
		}else{
			log.info(CMSConstants.REQUEST_INVALID);
		}
		return flag;
	}

}
